"""
分析相关的API路由
包含简历分析、背景核查、潜力评估等接口
"""

from fastapi import APIRouter, Depends, HTTPException, status
from typing import Dict, Any
from datetime import datetime

from ....core.interfaces import Task, TaskStatus
from ..models import *
from ..dependencies import analysis_dependencies

router = APIRouter(prefix="/api/v1/analysis", tags=["Analysis"])


@router.post("/resume/detailed", response_model=AnalysisResponse)
async def detailed_resume_analysis(
    request: ResumeAnalysisDetailRequest,
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """详细简历分析接口"""
    try:
        orchestrator = deps["orchestrator"]
        
        task = Task(
            id=f"detailed_resume_{datetime.now().timestamp()}",
            description=request.resume_content,
            task_type="detailed_resume_analysis",
            metadata={
                "job_description": request.job_description,
                "required_skills": request.required_skills,
                "preferred_experience": request.preferred_experience,
                "analysis_focus": request.analysis_focus
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            return AnalysisResponse(
                task_id=result_task.id,
                status="completed",
                result=result_task.result,
                processing_time={"total": 0.0}  # 简化
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Analysis failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Detailed resume analysis failed: {str(e)}"
        )


@router.post("/skill-assessment", response_model=AnalysisResponse)
async def skill_assessment(
    request: SkillAssessmentRequest,
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """技能评估接口"""
    try:
        orchestrator = deps["orchestrator"]
        
        task = Task(
            id=f"skill_assessment_{datetime.now().timestamp()}",
            description=request.candidate_info,
            task_type="skill_assessment",
            metadata={
                "target_skills": request.target_skills,
                "skill_weights": request.skill_weights
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            return AnalysisResponse(
                task_id=result_task.id,
                status="completed",
                result=result_task.result,
                processing_time={"total": 0.0}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Skill assessment failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Skill assessment failed: {str(e)}"
        )


@router.post("/comprehensive", response_model=ComprehensiveAssessmentResponse)
async def comprehensive_assessment(
    request: ComprehensiveAssessmentRequest,
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """综合评估接口"""
    try:
        orchestrator = deps["orchestrator"]
        
        task = Task(
            id=f"comprehensive_{datetime.now().timestamp()}",
            description=f"综合评估候选人",
            task_type="comprehensive_assessment",
            metadata={
                "candidate_data": request.candidate_data,
                "position_requirements": request.position_requirements,
                "assessment_modules": request.assessment_modules,
                "weightings": request.weightings
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            result = result_task.result
            return ComprehensiveAssessmentResponse(
                assessment_id=result_task.id,
                overall_score=result.get("overall_score", 0.0),
                module_scores=result.get("module_scores", {}),
                detailed_analysis=result.get("detailed_analysis", {}),
                recommendations=result.get("recommendations", []),
                risk_factors=result.get("risk_factors", []),
                hiring_decision=result.get("hiring_decision", "pending"),
                confidence_level=result.get("confidence_level", 0.0)
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Comprehensive assessment failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Comprehensive assessment failed: {str(e)}"
        )


@router.post("/code-evaluation", response_model=AnalysisResponse)
async def code_evaluation(
    request: Dict[str, Any],
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """代码评估接口"""
    try:
        orchestrator = deps["orchestrator"]
        
        code_content = request.get("code_content", "")
        programming_language = request.get("programming_language", "python")
        evaluation_type = request.get("evaluation_type", "comprehensive")
        candidate_name = request.get("candidate_name", "Unknown")
        
        task = Task(
            id=f"code_evaluation_{datetime.now().timestamp()}",
            description=f"代码评估任务",
            task_type="code_evaluation",
            metadata={
                "code_content": code_content,
                "programming_language": programming_language,
                "evaluation_type": evaluation_type,
                "candidate_name": candidate_name
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            return AnalysisResponse(
                task_id=result_task.id,
                status="completed",
                result=result_task.result,
                processing_time={"total": 0.0}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Code evaluation failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Code evaluation failed: {str(e)}"
        )


@router.post("/potential-prediction", response_model=AnalysisResponse)
async def potential_prediction(
    request: Dict[str, Any],
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """潜力预测接口"""
    try:
        orchestrator = deps["orchestrator"]
        
        candidate_data = request.get("candidate_data", {})
        prediction_timeframe = request.get("prediction_timeframe", "medium_term")
        focus_areas = request.get("focus_areas", ["all"])
        candidate_name = candidate_data.get("name", "Unknown")
        
        task = Task(
            id=f"potential_prediction_{datetime.now().timestamp()}",
            description=f"潜力预测分析",
            task_type="potential_prediction",
            metadata={
                "candidate_data": candidate_data,
                "prediction_timeframe": prediction_timeframe,
                "focus_areas": focus_areas,
                "candidate_name": candidate_name
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            return AnalysisResponse(
                task_id=result_task.id,
                status="completed",
                result=result_task.result,
                processing_time={"total": 0.0}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Potential prediction failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Potential prediction failed: {str(e)}"
        )


@router.post("/innovative-analysis", response_model=AnalysisResponse) 
async def innovative_analysis(
    request: Dict[str, Any],
    deps: Dict[str, Any] = Depends(analysis_dependencies)
):
    """创新分析接口 - 结合代码评估和潜力预测"""
    try:
        orchestrator = deps["orchestrator"]
        
        candidate_data = request.get("candidate_data", {})
        code_samples = request.get("code_samples", [])
        analysis_type = request.get("analysis_type", "comprehensive")
        
        task = Task(
            id=f"innovative_analysis_{datetime.now().timestamp()}",
            description=f"创新分析 - 综合代码评估和潜力预测",
            task_type="innovative_analysis",
            metadata={
                "candidate_data": candidate_data,
                "code_samples": code_samples,
                "analysis_type": analysis_type,
                "include_code_evaluation": len(code_samples) > 0,
                "include_potential_prediction": True
            }
        )
        
        result_task = await orchestrator.orchestrate_task(task)
        
        if result_task.status == TaskStatus.COMPLETED:
            return AnalysisResponse(
                task_id=result_task.id,
                status="completed",
                result=result_task.result,
                processing_time={"total": 0.0}
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Innovative analysis failed: {result_task.result.get('error', 'Unknown error')}"
            )
            
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Innovative analysis failed: {str(e)}"
        )